/*
   Copyright 2012 Shane Phillips

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.jdraw.utils;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Dialogs {

	public static enum FileSelectionMode {
		SAVE, OPEN
	};

	public static void showError(String title, String message) {
		JOptionPane.showMessageDialog(null, message, title,
				JOptionPane.ERROR_MESSAGE);

	}

	public static boolean showSavePrompt(String message) {
		int result = JOptionPane.showConfirmDialog(null, message, null,
				JOptionPane.YES_NO_OPTION);
		if (result == JOptionPane.YES_OPTION) {
			return true;
		}
		return false;
	}

	public static File selectFile(FileNameExtensionFilter filter,
			FileSelectionMode mode) throws IllegalArgumentException {

		// TODO: use preferences to remember last save / open directories
		File selectedFile = null;
		int fileOpenResult = JFileChooser.APPROVE_OPTION;

		JFileChooser fileOpenChooser = new JFileChooser();
		if (filter != null) {
			fileOpenChooser.addChoosableFileFilter(filter);
			fileOpenChooser.setFileFilter(filter);
		}

		if (mode == FileSelectionMode.OPEN) {
			fileOpenChooser.setDialogType(JFileChooser.OPEN_DIALOG);
			fileOpenResult = fileOpenChooser.showOpenDialog(null);
		} else if (mode == FileSelectionMode.SAVE) {
			fileOpenChooser.setDialogType(JFileChooser.SAVE_DIALOG);
			fileOpenResult = fileOpenChooser.showSaveDialog(null);

		} else {
			throw new IllegalArgumentException("Invalid FileSelectionMode");
		}

		if (fileOpenResult == JFileChooser.APPROVE_OPTION) {
			selectedFile = fileOpenChooser.getSelectedFile();
		} else {
			return null;
		}

		return selectedFile;
	}

}
